﻿using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
public class Monster : Character,IDamage {
	public int indexPath=0;
	Vector3 velcity;
	public EnemyInfo enemyInfo;
	public Action<int,int,int> hpOnChange;
	public Action<Monster> onDeath;
	public bool isDeath=false;
	int pathCount;
	public override void Awake() {
		base.Awake();
		enemyInfo.health=enemyInfo.maxHealth;
		isDeath=false;
		ObjectFactory.CreatHpUI("HP",(o)=>{
			HealthUI healthUI= o.GetComponent<HealthUI>();
			healthUI.BindHp(this);
		
		});
	}
	 private void Start() {
		pathCount= Path.pathManager.path.Count;
	}

	void Update(){
		
		MoveTo(Path.pathManager.path[indexPath]);
	}

	public void MoveTo(Vector3 target){
		Vector3 arr=target-transform.position;
		Vector3 dir=arr.normalized;
		float length=arr.magnitude;
	
		velcity=dir*enemyInfo.moveSpeed*Time.deltaTime;
		if(length>0.5f){
			controller.Move(velcity);
			Quaternion q=Quaternion.LookRotation(velcity);
			transform.rotation=Quaternion.Lerp(transform.rotation,q,Time.deltaTime*30);
		}
		else{
			//%(Path.pathManager.path.Count-1)
			if(indexPath<(pathCount-1)){
				indexPath++;
			}
		}
		
	}


    public void ToDamage(int Atk, Tower sender,Vector3 pos)
    {
		int oldHp=enemyInfo.health;
        enemyInfo.health=Mathf.Max(enemyInfo.health-Atk,0);
		if(hpOnChange!=null){
			hpOnChange(enemyInfo.health,oldHp,enemyInfo.maxHealth);
		}
		if(enemyInfo.health==0){
			OnDeath();
		}

		//播放受伤特效
		ObjectFactory.CreatEffect("Enemy_Damage",(o)=>{ o.transform.position = pos; });
    }

	public void OnDeath(){
		isDeath=true;
		//生成死亡特效和动画
		ObjectFactory.CreatEffect("Enemy_Damage1", (o) => { o.transform.position = transform.position; });
		//加金币
		GameManager.Instance.AddCoin(enemyInfo.price);
		//播放死亡动画

		//摧毁
		Destroy(gameObject);
		GameManager.Instance.RemoveEnemy(this.gameObject);
	}
	public void DestroySelf(){
		//掉血
		GameManager.Instance.UserDamage(enemyInfo.attackUser);
		isDeath=true;
		Destroy(gameObject);
		GameManager.Instance.RemoveEnemy(this.gameObject);
	}

}
